<template>
	<view class="contont">
		<nav-bar :title="pageInfo.navbarTitle" :iconLeft="true" />

		<uni-forms :model="form" :rules="rules" ref="refForm" labelAlign="right" label-width="90px">
			<view class="content-bgc">
				<view class="b-con">

					<uni-forms-item label="委外补发料单号" name="code" required>
						<view style="display: flex;gap:20rpx">
							<uni-easyinput v-model="form.code" placeholder="请输入委外补发料单号" class="iptBor" :inputBorder="false"
								:disabled="switchCode" />
							<view style="margin-left: 20rpx" v-show="pageInfo.type == 'add'">
								<u-switch v-model="switchCode" @change="switchChange" size="20" />
								自动生成
							</view>
						</view>
					</uni-forms-item>
					<view class="hint-text">只有“已审核”状态的委外加工单，才会出现在下拉框中</view>
					<uni-forms-item label="委外加工单号" name="machining" required>
						<uni-data-select mode="underline" placeholder="请选择委外加工单号" v-model="form.machining"
							:localdata="machining_list" :clear="true" :disabled="pageInfo.type == 'edit'" @change="order_change" />
					</uni-forms-item>
					<uni-forms-item label="发料日期" name="issue_date" required>
						<view class="dateTimeBottom">
							<uni-datetime-picker type="datetime" placeholder="发料日期" :clear-icon="false" v-model="form.issue_date"
								@show="car_popup_Show = false" @maskClick="car_popup_Show = true" @change="car_popup_Show = true"
								:border="false" />
						</view>
					</uni-forms-item>
					<uni-forms-item label="备注" name="desc">
						<uni-easyinput type="textarea" v-model="form.desc" placeholder="请输入备注" />
					</uni-forms-item>
				</view>
			</view>
			<view class="car-jiesuan" @click="car_popupShow = !car_popupShow" v-show="car_popup_Show">
				<view class="fotter-icon">
					<image class="cartIcon" src="@/static/adjust_icon_01.png"></image>
				</view>
				<view class="fotter-texts">
					<u--text type="info" :text="`产品数量：${form.product_list.length}`"></u--text>
				</view>
				<view class="fotter-btn" :class="{ btnBgc: Boolean(form.product_list.length) }" v-show="car_popupShow"
					@click.stop="save">提交</view>
				<view style="margin-left: auto;" v-show="!car_popupShow"><u--text text="点击查看" type="primary" suffixIcon="eye"
						iconStyle="font-size: 40rpx;color:#3c9cff" /></view>
			</view>
			<custom-popup :popupShow="car_popupShow" mode="bottom" title="发货产品" @close="car_popupShow = false" height="70vh">
				<z-paging v-if="car_popupShow" ref="paging_car" :refresher-enabled="false" :loading-more-enabled="false" :fixed="false"
					v-model="form.product_list" @query="queryList_car">
					<template #top>
						<view class="search">
							<view class="hint-text">本期发料数量应在 1 和 (需要发料数量 - 已发料数量) 之间</view>
						</view>
					</template>
					<uni-card v-for="(item, pindex) in form.product_list" :key="pindex" :title="item.name" :sub-title="item.code"
						margin="5px" spacing="0">
						<view class="ctent">规格：{{ item.specification }}</view>
						<view class="con">
							<view class="ctent ">基本单位：{{ item.unit_main }}</view>
							<view class="ctent ">加工单价(元)：{{ item.machining_price }}</view>
						</view>
						<view style="background-color: #f2f5f9;">
							<uni-card v-for="(val, cindex) in item.children" :key="cindex" :title="val.name" :sub-title="val.code"
								margin="5px" spacing="0">
								<view class="ctent">规格：{{ val.specification }}</view>
								<view class="con">
									<view class="ctent flex1">基本单位：{{ val.unit_main }}</view>
								</view>
								<view class="con">
									<view class="ctent flex1">需要发料数量：{{ val.num }}</view>
								</view>
								<view class="con">
									<view class="ctent">已发料数量：{{ val.up_num }}</view>
									<view class="ctent">已补发料量：{{ val.repair_num }}</view>
								</view>
								<uni-forms-item label="发料仓库：" :name="`product_list[${pindex}].children[${cindex}].warehouse`" required
									:rules="[{ required: true, errorMessage: `请选择【${val.name}】的发料仓库` }]">
									<uni-data-select mode="underline" placeholder="请选择发料仓库" v-model="val.warehouse"
										:localdata="getWarList(val.warehouse_list)" :clear="false"
										@change="handleWareChange($event, val)" />
								</uni-forms-item>
								<view class="con">
									<view class="ctent" style="flex: none;">本期补发量：</view>
									<custom-num-box v-model="val.now_num" :min="0" @change="changeNum($event, val)"
										:asyncChange="true"></custom-num-box>
								</view>
								<uni-forms-item label="补发原因：" :name="`product_list[${pindex}].children[${cindex}].cause`" required
									:rules="[{ required: true, errorMessage: `请选择【${val.name}】的补发原因` }]">
									<uni-data-select mode="underline" placeholder="请选择补发原因" v-model="val.cause" :localdata="cause_list"
										:clear="false" />
								</uni-forms-item>
								<view class="con">
									<view class="ctent" style="flex: none;">损坏扣费：</view>
									<custom-num-box v-model="val.fee_price" :min="0"></custom-num-box>
								</view>
							</uni-card>
						</view>
					</uni-card>
					<template #bottom>
						<view class="zhanwei"></view>
					</template>
				</z-paging>
			</custom-popup>
		</uni-forms>
	</view>
</template>
<script setup>
import { reactive, ref, getCurrentInstance } from 'vue';
import { onLoad } from '@dcloudio/uni-app'
import enMaterialTowApi from '../../../api/entrust/en_material_tow'
import { generateCode, debounce } from '@/utils/index.js';

const pageInfo = reactive({
	navbarTitle: '委外补发料出库',
	type: '',
	edit_id: null,
});

onLoad(option => {
	get_machining_list()
	pageInfo.type = option.type
	if (option.type == 'edit') {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(修改)'
		get_detail(option.id)
		pageInfo.edit_id = option.id
	} else {
		pageInfo.navbarTitle = pageInfo.navbarTitle + '(新增)'
		form.code = generateCode('TW')
	}
})

//自动生成按钮
const switchCode = ref(true);
function switchChange(v) {
	if (v) {
		form.code = generateCode('TW')
	}
}

const cause_list = ref([
	{ text: '服务商损坏', value: '服务商损坏' },
	{ text: '少发漏发', value: '少发漏发' },
	{ text: '运输损少', value: '运输损少' },
	{ text: '其他损少', value: '其他损少' }
])

const refForm = ref(null)
const form = reactive({
	code: '',
	machining: null,
	issue_date: null,
	desc: '',
	product_list: []
})
const fields = Object.keys(form);
const rules = {
	code: { rules: [{ required: true, errorMessage: '请填写委外补发料单号' }] },
	machining: { rules: [{ required: true, type: 'number', errorMessage: '请选择委外加工单' }] },
	issue_date: { rules: [{ required: true, errorMessage: '请填写发料日期' }] },
}

function get_detail(id) {
	console.log('idididid', id)
	enMaterialTowApi.machining_repair_detail(id).then(res => {
		const record = uni.$lodash.pick(res, fields)
		Object.assign(form, record)
		form.product_list = res.table_data.map(v => {
			v.children = v.children.map(k => {
				k.inventory = k.warehouse_list.find(v => v.id == k.warehouse).inventory
				return k
			})
			return v
		})
	})
}

function handleWareChange(v, row) {
	const obj = row.warehouse_list.find(k => k.id == v)
	row.inventory = obj.inventory
	if (row.now_num > row.inventory) {
		row.now_num = row.inventory
	}
}

function getWarList(list) {
	return list.map(v => ({
		text: v.info, value: v.id, inventory: v.inventory
	}))
}

function changeNum(e, row) {
	if (!row.warehouse) {
		return uni.$u.toast('请选择仓库')
	}
	if (e.value > row.inventory) {
		row.now_num = row.inventory
		return uni.$u.toast('本期领数量不能大于所选仓库库存')
	}
	if (e.value > row.num - row.up_num) {
		row.now_num = row.num - row.up_num
		return uni.$u.toast('本期发料数量应在 1 和 (需要发料数量 - 已发料数量) 之间')
	}
	row.now_num = e.value
}
function order_change(v) {
	form.product_list = []
	if (!v) {
		form.purchase_order = null
		return
	}
	enMaterialTowApi.machining_product_detail({ machining__id: v }).then(res => {
		form.product_list = res.results.map(v => {
			const children_list = v.machining_product_boms.map(k => {
				const warehouse_list = k.bom.stock_info.map(j => {
					return {
						id: j.warehouse_id,
						info: j.warehouse_name + '【' + j.unit_info + '】',
						inventory: j.inventory
					}
				})
				return {
					id: k.bom.id,
					id_info: 'bom_' + k.id,
					type: 'bom',
					code: k.bom.code,
					name: k.bom.name,
					specification: k.bom.specification,
					unit_main: k.bom.unit_main,
					bom_num: k.bom_num,
					machining_price: '-',
					num: k.num,
					repair_num: k.repair_num || 0,
					fee_price: k.fee_price || 0,
					cause: null,
					up_num: k.up_num,
					now_num: 0,
					warehouse_list: warehouse_list,
					warehouse: null,
					inventory: null,
				}
			})
			return {
				id: v.product.id,
				id_info: 'product_' + v.product.id,
				machining_product_id: v.id,
				type: 'product',
				code: v.product.code,
				name: v.product.name,
				specification: v.product.specification,
				unit_main: v.product.unit_main,
				bom_num: '-',
				machining_price: v.machining_price,
				num: '-',
				up_num: '-',
				now_num: '-',
				repair_num: '-',
				cause: '-',
				fee_price: '-',
				warehouse_list: '-',
				children: children_list
			}
		})
	})
}

const paging_car = ref(null)
const machining_list = ref([])
const car_popupShow = ref(false)
const car_popup_Show = ref(true)
function get_machining_list() {
	const params = { page: 1, page_size: 99999, status: '2' }
	enMaterialTowApi.get_machining(params).then(res => {
		machining_list.value = res.results.map(v => ({
			text: v.code,
			value: v.id
		}))
	})
}
//提交操作
function save() {
	refForm.value.validate().then(() => {
		const params = uni.$lodash.cloneDeep(form) // 深拷贝一份form表单
		if (pageInfo.type == 'add') {
			enMaterialTowApi.post_machining_repair(params).then(res => {
				uni.$u.toast('添加成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		} else {
			//修改
			enMaterialTowApi.patch_machining_repair(params, pageInfo.edit_id).then((res) => {
				uni.$u.toast('修改成功')
				setTimeout(() => {
					backRefsh();
				}, 1000)
			})
		}

	}).catch((error) => {
		uni.$u.toast(error[0].errorMessage);
	})
}
function queryList_car() {
	paging_car.value.complete(form.product_list);
}
//返回上一级并刷新上一级页面
function backRefsh() {
	uni.navigateBack({
		delta: 1, // 返回的页面层数，1 表示返回上一级
		success: () => {
			uni.$bus.useBusEmit('w_out_entrust_b:refresh')
		}
	})
}
</script>

<style lang="scss" scoped>
.date_text {
	width: 90px !important;
}
</style>